'use strict';
const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
const consts = require('consts')
const redis = uniCloud.redis()
const moment = require('moment-timezone');
moment.prototype.cnZone = function() {
	this.tz("Asia/Shanghai")
	return this
}

const getGoodsList = async (query1 = {}, query2 = {}) => {
	let res = await db.collection("t3ds-mall-goods").aggregate()
		.match(query1)
		.lookup({
			from: "t3ds-mall-sku",
			let: {
				goodsId: '$_id'
			},
			pipeline: $.pipeline()
				.match(dbCmd.expr($.and([
						$.eq(['$goods_id', '$$goodsId']),
						$.eq(['$is_on_sale', true])
					])
				))
				.sort({
					price: 1
				})
				.project({
					price: 1,
					self_buy_reward: 1,
					settlement_price: 1,
					share_reward: 1,
					share_reward3: 1,
					share_reward_old: 1,
					stock: 1,
					unrealSellCount: 1,
					sellCount: 1,
					soldRate: $.divide([$.add(['$unrealSellCount', '$sellCount', '$stock']), $.add(['$unrealSellCount', '$sellCount'])]),
					market_price: 1,
					is_on_seckill: 1,
					seckill_status: 1,
					endNowDate: 1,
					startNextDate: 1,
					upDate: 1,
					downDate: 1,
					startDate: 1,
					endDate: 1,
					gapTime: 1,
					buyTime: 1,
					amount: 1,
					amountNow: 1,
				})
				.done(),
			as: 'skus'
		})
		.project({
			_id: '$_id',
			name: '$name',
			thumb: '$thumb',
			category_id: '$category_id',
			is_time_limited: '$is_time_limited',
			sale_deadline: '$sale_deadline',
			hit_count: '$hit_count',
			is_new: '$is_new',
			new_up_deadline: '$new_up_deadline',
			new_down_deadline: '$new_down_deadline',
			sellInfo: {
				totalSellCount: '$totalSellCount',
				totalStock: '$totalStock',
				price: '$price',
				market_price: '$market_price'
			},
			order_no: '$order_no',
			create_time: '$create_time',
			update_time: '$update_time',
			skus: '$skus',
			distribution: '$distribution',
			stores: '$stores'
		})
		.match(query2)
		.sort({order_no: 1})
		// .skip((pageNum - 1) * pageSize)
		// .limit(pageSize)
		.end()
	return res.data
}

const getGoodsList2 = async (query) => {
	let res = await db.collection("t3ds-mall-goods").aggregate()
		.lookup({
			from: "t3ds-mall-sku",
			let: {
				goodsId: '$_id'
			},
			pipeline: $.pipeline()
				.match(dbCmd.expr($.and([
						$.eq(['$goods_id', '$$goodsId']),
						$.eq(['$is_on_sale', true])
					])
				))
				.sort({
					price: 1
				})
				.project({
					price: 1,
					self_buy_reward: 1,
					settlement_price: 1,
					share_reward: 1,
					share_reward3: 1,
					share_reward_old: 1,
					stock: 1,
					unrealSellCount: 1,
					sellCount: 1,
					soldRate: $.divide([$.add(['$unrealSellCount', '$sellCount', '$stock']), $.add(['$unrealSellCount', '$sellCount'])]),
					market_price: 1,
					is_on_seckill: 1,
					seckill_status: 1,
					endNowDate: 1,
					startNextDate: 1,
					upDate: 1,
					downDate: 1,
					startDate: 1,
					endDate: 1,
					gapTime: 1,
					buyTime: 1,
					amount: 1,
					amountNow: 1,
				})
				.done(),
			as: 'skus'
		})
		.project({
			_id: '$_id',
			name: '$name',
			thumb: '$thumb',
			category_id: '$category_id',
			is_on_sale: 1,
			is_time_limited: '$is_time_limited',
			sale_deadline: '$sale_deadline',
			hit_count: '$hit_count',
			is_new: '$is_new',
			new_up_deadline: '$new_up_deadline',
			new_down_deadline: '$new_down_deadline',
			sellInfo: {
				totalSellCount: '$totalSellCount',
				totalStock: '$totalStock',
				price: '$price',
				market_price: '$market_price'
			},
			order_no: '$order_no',
			create_time: '$create_time',
			update_time: '$update_time',
			skus: '$skus',
			distribution: '$distribution',
			stores: '$stores'
		})
		.match(query)
		.sort({order_no: 1})
		// .skip((pageNum - 1) * pageSize)
		// .limit(pageSize)
		.end()
	return res.data
}

exports.main = async (event, context) => {
	try {
		// await this.syncGoodsStatus();
		let result = {}
		//上新
		let query = {
			"is_on_sale": true,
			"is_new": true,
			"new_down_deadline": dbCmd.gt(Date.now())
		}
		let newGoodsList = await getGoodsList(query)
		console.log('newGoodsList', newGoodsList)
		let map = new Map()
		newGoodsList.forEach(item => {
			item.stores.forEach(s => {
				if (map.has(s.city)) {
					let list = map.get(s.city)
					list.push(item)
				} else {
					map.set(s.city, [item])
				}
			})
		})
		map.forEach(async (v, k) => {
			let key = consts.redisKeys.keyNewGoods + k
			await redis.del(key)
			v.forEach(async item => {
				redis.rpush(key, JSON.stringify(item))
			})
		})
		
		//所有已上架的限时抢购的商品（售卖时间不足2天）
		let threeTime = moment().tz("Asia/Shanghai").add(2, 'days').hour(
			23).minute(59).second(59).toDate().getTime()
		query = {
			"is_on_sale": true,
			"is_time_limited": true,
			"sale_deadline": dbCmd.gt(Date.now()).and(dbCmd.lt(threeTime))
		}
		let deadGoodsList = await getGoodsList(query)
		console.log('deadGoodsList', deadGoodsList)
		//库存不足百分之20的上架商品
		let soldoutGoodsList = await getGoodsList2({
			"is_on_sale": true,
			"is_time_limited": true
			}, {
				"skus.soldRate": dbCmd.gte(0.8)
			}
		)
		console.log('soldoutGoodsList', soldoutGoodsList)
		map = new Map()
		deadGoodsList.forEach(item => {
			item.stores.forEach(s => {
				if (map.has(s.city)) {
					let list = map.get(s.city)
					list.push(item)
				} else {
					map.set(s.city, [item])
				}
			})
		})
		soldoutGoodsList.forEach(item => {
			item.stores.forEach(s => {
				if (map.has(s.city)) {
					let list = map.get(s.city)
					list.push(item)
				} else {
					map.set(s.city, [item])
				}
			})
		})
		map.forEach(async (v, k) => {
			let key = consts.redisKeys.keySoldout + k
			await redis.del(key)
			v.forEach(async item => {
				redis.rpush(key, JSON.stringify(item))
			})
		})
		// let countList = await this.getList(query3, sort, city, 1, 99, userLocation);
		// for(let i = 0 ; i < countList.length ;i++) {
		// 	let res = countList[i].sellInfo.totalSellCount/countList[i].sellInfo.totalStock
		// 	if(res >= 0.8) {
		// 		saleGoodList.push(countList[i])
		// 	}
		// }
		// if (token) {
		// 	newGoodList = await this.getGoodRebate(newGoodList,token)
		// 	saleGoodList = await this.getGoodRebate(saleGoodList,token)
		// }
		// result.saleEndGoodList = saleGoodList
		// return result
	} catch (e) {
		console.error(e)
	}
};
